package com.jch.har.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ClientHandler extends ChannelInboundHandlerAdapter {

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(dateFormat.format(new Date()) + " 客户端: " + ctx.channel().localAddress().toString() + " 连接到服务器: " + ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.err.println(dateFormat.format(new Date()) + " 断开连接重连: " + ctx.channel().remoteAddress().toString());
        // 使用过程中重连
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(dateFormat.format(new Date()) + " ClientHandler.channelInactive 开始执行重连操作");
                    new NettyClient().connect("127.0.0.1", 1131);
                    System.out.println(dateFormat.format(new Date()) + " netty client start done.");
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    System.err.println(dateFormat.format(new Date()) + " netty client start error go reconnect...");
                }
            }
        }).start();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(dateFormat.format(new Date()) + " 客户端收到消息: " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println(dateFormat.format(new Date()) + " 出现异常: " + cause.getMessage());
        ctx.close();
    }
}
